package com.test.com.bluetoothchatandroid.receiver;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;

import com.test.com.bluetoothchatandroid.callback.BluetoothScanCallback;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by ${cs} on 2018/4/17.
 * @author saviorT
 * bluetooth scan
 */

public class ScanBluetoothBroadcastReceiver extends BroadcastReceiver {
	private BluetoothScanCallback<BluetoothDevice> scanCallback;
	private final Map<String,BluetoothDevice> mDeviceMap = new HashMap<>();

	public ScanBluetoothBroadcastReceiver(BluetoothScanCallback<BluetoothDevice> scanCallback) {
		this.scanCallback = scanCallback;
	}

	@Override
	public void onReceive(Context context, Intent intent) {
		if (scanCallback == null){
			return;
		}
		if (intent.getAction().equals(BluetoothDevice.ACTION_FOUND)){
			// get scan result
				BluetoothDevice bluetoothDevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
				if (bluetoothDevice == null){
					return;
				}
				if (!mDeviceMap.containsKey(bluetoothDevice.getAddress())){
					mDeviceMap.put(bluetoothDevice.getAddress(),bluetoothDevice);
				}
				scanCallback.discoverDevice(bluetoothDevice);
		}else if (intent.getAction().equals(BluetoothAdapter.ACTION_DISCOVERY_FINISHED)){
			// ending scan
			final List<BluetoothDevice> deviceList = new ArrayList<>(mDeviceMap.values());
			if (deviceList != null && deviceList.size()>0){
				scanCallback.scanFinish(deviceList);
			}else {
				scanCallback.scanTimeout();
			}
		}
	}
}
